package cloud.demarcia.rabbitregister.controller;

import cloud.demarcia.rabbitregister.service.LoginService;
import cloud.demarcia.rabbitregister.vo.UserLoginVo;
import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Bojun Wen, wen_bj@outlook.com
 * @date 2022.02.18
 */
@CrossOrigin
@RestController
@Slf4j
public class LoginController {

    @Resource
    private LoginService loginService;

    @GetMapping("/captcha")
    public ResponseEntity<String> getCaptcha(HttpServletResponse response) throws IOException {
        AbstractCaptcha captcha=getCaptcha();
        response.addHeader("code", captcha.getCode());
        captcha.write(response.getOutputStream());
        response.getOutputStream().close();
        return ResponseEntity.ok().build();
    }

    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody UserLoginVo vo) {
        log.info("登录请求：user:{},pass:{}",vo.getUsername(),vo.getPassword());
        String token=loginService.getToken(vo);
        log.info("成功生成了token!");
        return ResponseEntity.ok(token);
    }


    private AbstractCaptcha getCaptcha(){
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100);
        captcha.setGenerator(randomGenerator);
        return captcha;
    }

}
